package design.onekey.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import design.onekey.base.*;
import design.onekey.constant.Constants;
import design.onekey.constant.enums.DelFlagEnum;
import design.onekey.constant.StatusCode;
import design.onekey.exception.BizException;
import design.onekey.mapper.UserAccountMapper;
import design.onekey.mapper.UserAccountOrgMapper;
import design.onekey.mapper.UserAccountUserRoleMapper;
import design.onekey.model.UserAccount;
import design.onekey.model.UserAccountUserRole;
import design.onekey.model.dto.UserInfoDto;
import design.onekey.model.dto.UserAccountDto;
import design.onekey.model.dto.UserAccountOrg;
import design.onekey.model.dto.UserWithOrgRoleDto;
import design.onekey.service.ISysOrgService;
import design.onekey.service.IUserAccountService;
import design.onekey.util.Md5Util;
import design.onekey.util.MessageUtil;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
* @Description: UserAccount服务实现
* @author
* @date 2020-06-05 04:03:19
* @version V1.0
*/
@Service
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements IUserAccountService {

   @Autowired
   private ISysOrgService sysOrgService;

   @Autowired
   private UserAccountOrgMapper userAccountOrgMapper;

   @Autowired
   private UserAccountUserRoleMapper userAccountUserRoleMapper;

   /**
   * @Title: tablePagingQuery
   * @Description: 表格分页查询
   * @param @param model
   * @return BaseEntity
   * @author
   * @throws
   */
   @Override
   public PageEntity tablePagingQuery(UserAccount model) {
       PageEntity result = new PageEntity();
       model.setDelFlag(DelFlagEnum.UNDEL.getCode());
       com.github.pagehelper.Page<?> page = PageHelper.startPage(model.getCurrentPage(), model.getPageSize()); //分页条件
       List<UserAccount> list = this.baseMapper.searchDataLike(model);
       result.setData(list);
       result.setTotal(page.getTotal());
       result.setCurrentPage(model.getCurrentPage());
       result.setPageSize(model.getPageSize());
       return result;
   }


   /**
   *<p>Title: getDetail</p>
   *<p>Description: 获取详情</p>
   * @author
   * @param id
   * @return
   */
   @Override
   public BaseEntity getDetail(Long id) {
       return this.baseMapper.getDetail(id);
   }

   /**
   *<p>Title: insert</p>
   *<p>Description: 新增数据并校验</p>
   * @author
   * @param model
   * @return
   */
   @Transactional
   @Override
   public BaseEntity insert(UserWithOrgRoleDto model, UserInfoDto userInfoDto) {
       if (this.checkRepeat(new QueryWrapper<UserAccount>().eq("account_name", model.getAccountName())
               .eq("del_flag",DelFlagEnum.UNDEL.getCode()),q->this.baseMapper.selectCount(q) != 0)){
           throw new BizException(StatusCode.CHECK_FAILURE,MessageUtil.getValue("error.check.exist",new String[]{"账户名"}));
       }
       if (this.checkRepeat(new QueryWrapper<UserAccount>().eq("user_mobile", model.getUserMobile())
               .eq("del_flag",DelFlagEnum.UNDEL.getCode()),q->this.baseMapper.selectCount(q) != 0)){
           throw new BizException(StatusCode.CHECK_FAILURE, MessageUtil.getValue("error.check.exist",new String[]{"手机号"}));
       }
       if (StringUtil.isNullOrEmpty(model.getUserPwd())){
           model.setUserPwd(Md5Util.generateMd5(Md5Util.generateMd5(Constants.DEFAULT_PASSWORD)));
       }else {
           model.setUserPwd(Md5Util.generateMd5(Md5Util.generateMd5(model.getUserPwd())));
       }
       BaseEntity result = new BaseEntity();
       //保存用户
       this.save(model);
       //保存用户组织机构关系
       model.getOrgIds().forEach(
           p->{
               UserAccountOrg userAccountOrg = new UserAccountOrg();
               userAccountOrg.setUserAccountId(model.getId());
               userAccountOrg.setOrgId(p);
               userAccountOrgMapper.insert(userAccountOrg);
           }
       );
       //保存用户角色关系
       UserAccountUserRole userAccountUserRole = new UserAccountUserRole();
       userAccountUserRole.setUserId(model.getId());
       userAccountUserRole.setRoleId(model.getRoleId());
       userAccountUserRoleMapper.insert(userAccountUserRole);
       result.setStatusMsg(MessageUtil.getValue("info.insert"));
       return result;
   }

   /**
   *<p>Title: update</p>
   *<p>Description: 更新数据并校验</p>
   * @author
   * @param model
   * @return
   */
   @Transactional
   @Override
   public BaseEntity update(UserWithOrgRoleDto model,UserInfoDto userInfoDto) {
       if (this.checkRepeat(new QueryWrapper<UserAccount>().eq("account_name", model.getAccountName())
               .eq("del_flag",DelFlagEnum.UNDEL.getCode())
               .ne("id",model.getId()),q->this.baseMapper.selectCount(q) != 0)){
           throw new BizException(StatusCode.CHECK_FAILURE,MessageUtil.getValue("error.check.exist",new String[]{"账户名"}));
       }
       if (this.checkRepeat(new QueryWrapper<UserAccount>().eq("user_mobile", model.getUserMobile())
               .eq("del_flag",DelFlagEnum.UNDEL.getCode())
               .ne("id",model.getId()),q->this.baseMapper.selectCount(q) != 0)){
           throw new BizException(StatusCode.CHECK_FAILURE,MessageUtil.getValue("error.check.exist",new String[]{"手机号"}));
       }

//		model.setUserPwd(Md5Util.generateMd5(model.getUserPwd()));
       BaseEntity result = new BaseEntity();
       //更新用户
       this.updateById(model);
       //删除旧组织机构和用户
       List<UserAccountOrg> userAccountOrgs = this.userAccountOrgMapper.selectList(new QueryWrapper<UserAccountOrg>().eq("user_account_id", model.getId()).eq("del_flag", 1));
       userAccountOrgs.forEach(p->{
           p.setDelFlag(DelFlagEnum.DEL.getCode());
           userAccountOrgMapper.updateById(p);
       });
       //保存新用户组织机构关系
       model.getOrgIds().forEach(
               p->{
                   UserAccountOrg userAccountOrg = new UserAccountOrg();
                   userAccountOrg.setUserAccountId(model.getId());
                   userAccountOrg.setOrgId(p);
                   userAccountOrgMapper.insert(userAccountOrg);
               }
       );
       //更新用户和角色关系
       UserAccountUserRole userAccountUserRole = new UserAccountUserRole();
       userAccountUserRole.setRoleId(model.getRoleId());
       userAccountUserRoleMapper.update(userAccountUserRole,new UpdateWrapper<UserAccountUserRole>().eq("user_id",model.getId()));
       result.setStatusMsg(MessageUtil.getValue("info.update"));
       return result;
   }

   /**
   *<p>Title: delete</p>
   *<p>Description: 单条删除数据</p>
   * @author
   * @param model
   * @return
   */
   @Transactional
   @Override
   public BaseEntity delete(Long id) {
       UserAccount userAccount = new UserAccount();
       userAccount.setId(id);
       userAccount.setDelFlag(DelFlagEnum.DEL.getCode());
       this.updateById(userAccount);
       BaseEntity result = new BaseEntity();
       result.setStatusMsg(MessageUtil.getValue("info.delete"));
       return result;
   }

   /**
   *<p>Title: deleteBatch</p>
   *<p>Description: 批量删除数据</p>
   * @author
   * @param list
   * @return
   */
   @Transactional
   @Override
   public BaseEntity deleteBatch(List<Long> ids) {
       List<UserAccount> list = new ArrayList<UserAccount>();
       for (int i = 0; i < ids.size(); i++) {
           UserAccount userAccount = new UserAccount();
           userAccount.setId(ids.get(i));
           userAccount.setDelFlag(DelFlagEnum.DEL.getCode());
           list.add(userAccount);
       }
       BaseEntity result = new BaseEntity();
       if (list != null && list.size() > 0) {
           this.updateBatchById(list);
       }
       result.setStatusMsg(MessageUtil.getValue("info.delete"));
       return result;
   }

    /**
     * @Method tablePagingQueryByAuthority
     * @Author zhangcheng
     * @Version  1.0
     * @Description 根据用户权限查询用户列表
     * @Return com.baiyyy.yfz.base.BaseEntity
     * @Exception
     * @Date 2020-6-10 11:36
     */
    @Override
    public BaseEntity tablePagingQueryByAuthority(UserAccount model, UserInfoDto userInfoDto) {
        PageEntity result = new PageEntity();
       //只能查询该用户权限下组织机构下的用户
        //加载所有组织机构
        //非删除
        model.setDelFlag(DelFlagEnum.UNDEL.getCode());
        UserWithOrgRoleDto userWithOrgDto = new UserWithOrgRoleDto();
        BeanUtils.copyProperties(model,userWithOrgDto);
        //判断是不是超级管理员
        if (userInfoDto.getIsAdmin() == 1){
            userWithOrgDto.setOrgIds(null);
        }else{
            //查询出所有的组织机构
            HashSet<Long> rids = new HashSet<>();
            Long orgId = userInfoDto.getOrgId();
            List<Long> orgIds = new ArrayList<Long>();
            orgIds.add(orgId);
            sysOrgService.loadAllOrgByIds(orgIds,rids);
            userWithOrgDto.setOrgIds(rids);
        }
        com.github.pagehelper.Page<?> page = PageHelper.startPage(model.getCurrentPage(), model.getPageSize()); //分页条件
        List<UserWithOrgRoleDto> userWithOrgDtos = this.baseMapper.tablePagingQueryByAuthority(userWithOrgDto);
        result.setData(userWithOrgDtos);
        result.setTotal(page.getTotal());
        result.setCurrentPage(model.getCurrentPage());
        result.setPageSize(model.getPageSize());
        return result;
    }

    /**
     * @Method resetPwd
     * @Author zhangcheng
     * @Version  1.0
     * @Description 根据用户id重置密码
     * @Return com.baiyyy.yfz.base.BaseEntity
     * @Exception
     * @Date 2020-6-12 9:18
     */
    @Override
    @Transactional
    public BaseEntity resetPwd(Long id) {
         BaseEntity result = new BaseEntity();
         UserAccount userAccount = new UserAccount();
         userAccount.setId(id);
         userAccount.setUserPwd(Md5Util.generateMd5(Md5Util.generateMd5(Constants.DEFAULT_PASSWORD)));
        this.baseMapper.updateById(userAccount);
        result.setStatusMsg(MessageUtil.getValue("info.reset.password"));
        return result;
    }


   /**
    * @Title: changePwd
    * @Description: 修改密码
    * @param userAccountDto
    * @param userInfoDto
    * @return
    * @author blcloak
    * @date 2020-06-12 01:31:45
    */
   @Override
   @Transactional
   public BaseEntity changePwd(UserAccountDto userAccountDto, UserInfoDto userInfoDto) {
       BaseEntity result = new BaseEntity();
       //获取当前用户信息
       UserAccount userAccount = this.getById(userInfoDto.getUserId());
       //判断旧密码是否输入正确
       if (!Md5Util.generateMd5(userAccountDto.getOldPwd()).equals(userAccount.getUserPwd())) {
           throw new BizException(StatusCode.FAILURE, MessageUtil.getValue("error.oldpwd"));
       }
       userAccount = new UserAccount();
       userAccount.setUserPwd(Md5Util.generateMd5(userAccountDto.getNewPwd()));
       userAccount.setId(userInfoDto.getUserId());
       this.updateById(userAccount);
       result.setStatusMsg(MessageUtil.getValue("info.changepwd"));
       return result;
   }


   /**
    * @Title: updateStatus
    * @Description: 启用停用
    * @param userAccount
    * @return
    * @author blcloak
    * @date 2020-06-23 07:44:53
    */
   @Override
   public BaseEntity updateStatus(UserAccount userAccount) {
       BaseEntity result = new BaseEntity();
       UserAccount param = new UserAccount();
       param.setId(userAccount.getId());
       param.setStatus(userAccount.getStatus());
       this.updateById(param);
       result.setStatusMsg(MessageUtil.getValue("info.operation"));
       return result;
   }
}
